package com.his.config.intercepors;

import com.xiao.common.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.List;

/**
 * @Author xiaoxiaoping
 * @Date 2020/2/4 15:37
 * @Version 1.0
 */
@RestControllerAdvice
public class ValidationInterceptor extends ResponseEntityExceptionHandler {
    private  final Logger logger = (Logger) LoggerFactory.getLogger(this.getClass());
    @Override
    public ResponseEntity<Object> handleBindException(
            BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return new ResponseEntity<>(getError(ex.getBindingResult().getAllErrors()), status);
    }

    /**
     * 解决 JSON 请求统一返回参数
     */
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return new ResponseEntity<>(getError(ex.getBindingResult().getAllErrors()) , status);
    }

    private ResultUtil getError(List<ObjectError> allErrors) {
        StringBuffer message = new StringBuffer();
        for(ObjectError error: allErrors){
            message.append(error.getDefaultMessage()).append(" & ");
        }
        logger.error(message.substring(0, message.length() - 3));  // 因为&两边空格
        return ResultUtil.FAIL(message.substring(0, message.length() - 3),null);
    }
}
